<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
           
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card >

            <el-row :gutter="20">

                <el-col :span="10">
                    <!-- 搜索框 -->
                    <el-input placeholder="请输入内容"  class="input-with-select" 
                     v-model="queryInfo.query" clearable @clear="getUserList">   
                         <el-button  icon="el-icon-search" slot="append"
                @click="getUserList"
                   ></el-button>
                    </el-input>
                     
                </el-col>
                
                <el-col :span="4">
                    <el-button @click="addDialogVisible = true"  type="primary">添加用户</el-button>
                </el-col>

                <template #append>
                    <el-button icon="el-icon-search"></el-button>
                </template>

            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="userlist" border height="500">
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态" prop="">
                    <template slot-scope="scope">
                        <!-- {{scope.row}} -->
                        <el-switch v-model="scope.row.mg_state"
                        @change="userStateChange(scope.row)"
                         active-color="#13ce66" inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="220px">
                    <!-- <template slot-scope="scopt"></template> -->

                   <template slot-scope="scope"> 

                    <el-tooltip effect="dark"
                    :enterable="false"
                        content="修改"
                        placement="top-start">
                        <el-button type="primary" icon="el-icon-edit"
                        @click="showEdit(scope.row.id)"></el-button>
                    </el-tooltip>

                    <el-tooltip effect="dark"
                    :enterable="false"
                        content="配置角色"
                        placement="top-start">
                        <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
                    </el-tooltip>

                     <el-tooltip effect="dark"
                     :enterable="false"
                        content="删除"
                        placement="top-start" >
                        <el-button type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
                    </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog @close="addDialogClose"
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%">
        <!-- 内容 -->
        <el-form :model="addForm" :rules="ruleaddForm" 
        ref="ruleFormRef" label-width="80px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
           </el-form-item>
           <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password" ></el-input>
           </el-form-item>
            <el-form-item label="确认密码" prop="passwords">
                <el-input type="password" v-model="addForm.passwords"></el-input>
            </el-form-item>
           <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
           </el-form-item>
           <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
           </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog
            title="修改用户"
            :visible.sync="editdialogVisible"
            width="50%" @close="addEditClose">

            <el-form ref="editFormRef" :model="addEdit" label-width="80px" :rules="ruleaddForm" >
                <el-form-item label="用户名">
                    <el-input v-model="addEdit.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addEdit.email" ></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addEdit.mobile" ></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfoe">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配角色对话框 -->
        <el-dialog
            title="分配角色"
            :visible.sync="setRoleDialogVisible"
            width="50%" @close="setRoleClose">

            <div>
                <p>当前用户：{{userInfo.username}}</p>
                <p>当前角色：{{userInfo.role_name}}</p>
                <p>分配角色：
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <el-option
                            v-for="item in rolesList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                        </el-option>
                   </el-select>
                </p>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleId">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

export default {
    data(){
        // 验证邮箱规则
        var checkemail = (rule, value, cb) =>{
            const regemail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

            if(regemail.test(value)){
                // 合法邮箱
                return cb()
            }

            cb(new Error('请输入合法邮箱'))
        }

        // 验证手机号的规则
        var checkmobile = (rule, value, cb) =>{
            const regmobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/

            if(regmobile.test(value)){
             
                // 合法手机号
                return cb()
            }

            cb(new Error('请输入合法手机号'))
        }

        // 验证两次密码一致
       var checkPasswords = (rule, value, cb) =>{
         
            if (value === '') {
          cb(new Error('请再次输入密码'));
          this.$message.error(this.addForm.password)
        } else if (value !== this.addForm.password) {
            
          cb(new Error('两次输入密码不一致!'));
        } else {
          cb();
        }
        }

        return {
            // select选择的值
            selectRoleId:'',

            // 所以角色的信息
            rolesList:[],

            // 查询到的用户信息
            addEdit:{},

            // 分配角色的用户信息
            userInfo:{},

            // 获取用户列表的参数对象
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:2
            },
            userlist:[],
            total:0,
            // 添加用户对话框
            addDialogVisible:false,
            // 修改用户信息对话框
            editdialogVisible:false,
            // 分配角色对话框
            setRoleDialogVisible:false,
            addForm:{
                // 确认密码
                passwords:'',
                username:'',
                password:'',
                email:'',
                mobile:''
            }, //表单
            ruleaddForm:{
                username:[
                    {required:true, message:'请输入用户名', trigger:'blur'}, {
                        min:3 , max:10,message:'用户名长度在3-10个字符之间', trigger:'blur'
                    }
                ],
                password:[
                     {required:true, message:'请输入密码', trigger:'blur'}, {
                        min:6 , max:15,message:'密码长度在6-15个字符之间', trigger:'blur'
                    }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {validator:checkemail, trigger:'blur'}
                 ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:checkmobile, trigger:'blur'}
                 ],
                passwords:[
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                     {validator:checkPasswords, trigger:'blur'}
                ]
            }  //表单验证规则
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
        // 获取用户列表
        async getUserList(){
            const {data:res} = await this.$http.get('users',{ params: this.queryInfo})
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('获取用户列表失败')
            this.userlist = res.data.users
            this.total = res.data.total
            // console.log(res);
        },

        // element自带
        // 监听pagsize改变的事件
        handleSizeChange(newSize){
            // console.log(newSize);
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },

        // 监听页码
        handleCurrentChange(newPage){
            // console.log(newPage);
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },

        // 监听Switch开关状态
        async userStateChange(userinfo){
            // console.log(userinfo);
            
            const {data:res} =await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}/`)
            if(res.meta.status !== 200){
                userinfo.me_state = !userinfo.me_state
                return this.$message.error('更新用户状态失败')
            }
            this.$message.success('更新用户状态成功！')
        },

        // 监听用户对话框关闭事件
        addDialogClose(){
            this.$refs.ruleFormRef.resetFields()
        },

        // 点击确认，添加新用户
        addUser(){
            // let {passwords, ...addForms} = this.addForm
            // console.log(addForms);
            // console.log(this.addForm);
            this.$refs.ruleFormRef.validate(async valid =>{
                // console.log(valid);
                // 表单校验成功可以发起添加用户请求
                if(!valid) return

                const {data:res} =await this.$http.post('users',this.addForm)

                if(res.meta.status !== 201){
                    this.$message.error('添加用户失败！')
                }
                this.$message.success('添加用户成功')
                // 隐藏对话框
                this.addDialogVisible = false;
                // 刷新用户表
                this.getUserList()
            })
            
        },
        async showEdit(id){
            const {data:res} = await this.$http.get('users/' + id)
            if(res.meta.status !==200){return this.$message.error('查询用户信息失败！')}

            this.addEdit = res.data
            this.editdialogVisible = true
            // console.log(id);

        },
        // 关闭对话框的时候重置
        addEditClose(){
            this.$refs.editFormRef.resetFields()
        },

        // 修改用户表单提交
        editUserInfoe(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return

                // 发起修改用户信息的数据请求
                const {data:res} = await this.$http.put('users/' + this.addEdit.id ,{
                    email:this.addEdit.email,
                    mobile:this.addEdit.mobile
                })

                if(res.meta.status !==200){
                    return this.$message.error('更新用户数据失败!')
                }

                // 关闭对话框
                this.editdialogVisible = false;

                // 更新用户表
                this.getUserList()

                // 提示
                this.$message.success('更新用户数据成功!')

            })
        },

        // 删除用户
        async removeUserById(id){
         const resCan =  await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
        
        }).then((resCan) => resCan
        ).catch((err) => err);

        // console.log(res);

        if(resCan === 'cancel'){
            return this.$message({
            type: 'info',
            message: '已取消删除'
          });
        }
        
          
         const {data:res} = await this.$http.delete('users/' + id)

         if(res.meta.status !== 200){
             return this.$message.error('删除用户失败！')
         }

         this.$message({
            type: 'success',
            message: '删除成功!'
          });

            this.getUserList()

        },

        // 分配角色 获取点击的角色 分配权限信息
        async setRole(role){
            // console.log(role);
            this.userInfo = role

            // 展示对话框之前获取所有角色的列表
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status !== 200){
                return this.$message.error('获取角色信息失败！')
            }

            this.rolesList = res.data

            this.setRoleDialogVisible = true
        },

        // 选择角色后保存，发送到后端
        async saveRoleId(){
            if(!this.selectRoleId){
                return this.$message.error('请选择要分配的角色!')
            }

            const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
                rid:this.selectRoleId
            })

            if(res.meta.status !== 200){
                return this.$message.error('分配角色失败!')
            }

            this.$message.success('更新角色成功!')
            this.getUserList()
            this.setRoleDialogVisible = false
        },

        // 关闭分配角色对话框，close 重置
        setRoleClose(){
            this.selectRoleId = ''
            this.userInfo = {}
        }
        

    }
}
</script>

<style lang="less" scoped>

</style>